package com.lj.tools.util;

import org.springframework.util.StringUtils;

import java.io.*;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {


    public static ZipUtil newInstance(String path) throws FileNotFoundException {
        return newInstance(new File(path));
    }

    public static ZipUtil newInstance(File file) throws FileNotFoundException {
        ZipUtil zipUtil = new ZipUtil();
        zipUtil.createZip(new FileOutputStream(file));
        return zipUtil;
    }

    private ZipOutputStream zipOutputStream;

    private void createZip(OutputStream out){
        zipOutputStream = new ZipOutputStream(out);
    }


    /**
     * 关闭
     */
    public void close() throws IOException {
        if (Objects.nonNull(zipOutputStream)){
            zipOutputStream.close();
        }
    }

    /**
     * 执行压缩
     * */
    public void compress(File file) throws IOException {
        compress(file, "");
    }

    public void compress(File file, String dirPath) throws IOException {
        if (StringUtils.hasLength(dirPath) && !dirPath.endsWith(File.pathSeparator)){
            dirPath = dirPath+File.pathSeparator;
        }

        if (file.isDirectory()){
            File[] files = file.listFiles();
            assert files != null;
            for(File sub:files){
                compress(sub, dirPath+file.getName());
            }
        }else{
            FileInputStream reader = null;
            try{
                ZipEntry zipEntry = new ZipEntry(dirPath+file.getName());
                zipOutputStream.putNextEntry(zipEntry);
                byte[] bytes = new byte[1024];
                int count = 0;
                reader = new FileInputStream(file);
                while (true){
                    count = reader.read(bytes);
                    if (count == 0 || count == -1){
                        break;
                    }
                    zipOutputStream.write(bytes, 0, count);
                }
                reader.close();
            }finally {
                if (Objects.nonNull(reader)){
                    reader.close();
                }
            }

        }
    }

}
